using System;
using System.Collections;
using System.Collections.Generic;
using Newtonsoft.Json;
using UnityEngine;
using XFABManager;

namespace XFGameFramework
{

    public enum StartingModuleSteps
    { 
        /// <summary>
        /// 加载配表
        /// </summary>
        PreloadConfigTables,

        /// <summary>
        /// 加载场景
        /// </summary>
        LoadScene
    }


    public class StartUpModuleRequest : CustomAsyncOperation<StartUpModuleRequest>
    {
         
        public StartingModuleSteps Step { get;private set; }
         
        internal IEnumerator StartUp(Module module) 
        {
            if (module == null)
            {
                Completed("无法启动空模块！");
                yield break;
            }

            ModuleManager.AddModule(module);

            progress = 0;

            Step = StartingModuleSteps.PreloadConfigTables;

            // 加载配表
            if (module.PreloadConfigTables != null && module.PreloadConfigTables.Count != 0)
            {
                float allCount = module.PreloadConfigTables.Count;
                float currentCount = 0;
                foreach (string asset_name in module.PreloadConfigTables.Keys)
                {
                    LoadAssetRequest request = AssetBundleManager.LoadAssetAsync<TextAsset>(module.ProjectName, asset_name);
                    yield return request;

                    if (request == null || !string.IsNullOrEmpty(request.error))
                    {
                        Debug.LogErrorFormat("BaseModule配表:{0}加载失败:{1}", asset_name, request != null ? request.error : string.Empty);
                        continue;
                    }

                    TextAsset text = request.asset as TextAsset;

                    if (text == null || string.IsNullOrEmpty(text.text))
                    {
                        Debug.LogWarningFormat("配表:{0} 数据为空!", asset_name);
                        continue;
                    }

                    Model[] models = null;

                    try
                    {
                        // 把 json 转成对应的对象 
                        models = JsonConvert.DeserializeObject(text.text, module.PreloadConfigTables[asset_name]) as Model[];
                        if (models == null || models.Length == 0) continue;
                    }
                    catch (Exception e)
                    {
                        // 卸载资源
                        AssetBundleManager.UnloadAsset(text);
                        Completed(string.Format("json解析异常:content:{0} error:{1}", text.text,e.ToString()));
                        yield break;
                    }

                    // 卸载资源
                    AssetBundleManager.UnloadAsset(text);

                    foreach (var model in models)
                    {
                        module.AddModel(model);
                    }

                    currentCount++;
                    progress = currentCount / allCount * 0.5f; // 更新进度
                }
            }
             

            Step = StartingModuleSteps.LoadScene;

            // 加载默认场景
            if (!string.IsNullOrEmpty(module.DefaultStartUpScene))
            {
                //startMessage = "正在加载场景...";
                AsyncOperation operation = AssetBundleManager.LoadSceneAsync(module.ProjectName, module.DefaultStartUpScene, UnityEngine.SceneManagement.LoadSceneMode.Single);
                while (operation != null && !operation.isDone)
                {
                    yield return null;
                    progress = 0.5f + operation.progress * 0.5f;
                }

            }

            try
            {
                module.OnStart();
            }
            catch (Exception)
            {
            }

            Completed();
        }

      

    }

}